package aspect;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;






import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;

import pojo.Customer;
/**
 * DigestAspect:LoginPwdAspect+RegistPwdAspect
 * 
 * */

@Component
@Aspect
public class DigestAspect {
	private final String pointcutLogin="execution(* controller.CustomerController.login(..))";
	private final String pointcutRegist="execution(* controller.CustomerController.signup(..))";
	private MessageDigest digest;
	public DigestAspect(){
		try {
			digest = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@Around(value=pointcutLogin)
	public Object loginAround(ProceedingJoinPoint point){
		Customer c = (Customer)point.getArgs()[0];
		Model model = (Model)point.getArgs()[1];
		String pwd=c.getPwd();
		System.out.println("log round c.pwd:"+pwd);
		Object object = null;
		System.out.println("log round before...");
		String newPwd = encrypt(pwd);
		c.setPwd(newPwd);
		try {
			//call target
			object = point.proceed(new Object[]{c,model});
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("log round after...");
		return object;
	}
	
	@Around(value=pointcutRegist)
	public Object registAround(ProceedingJoinPoint point){
		Customer c = (Customer)point.getArgs()[0];
		System.out.println("log round c.pwd:"+c.getPwd());
		Object object = null;
		System.out.println("log round before...");
		String newPwd = encrypt(c.getPwd());
		c.setPwd(newPwd);
		try {
			//call target
			object = point.proceed(new Object[]{c});
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("log round after...");
		return object;
	}
	
	private String encrypt(String pwd){
		String newPwd =null;
		try {
			byte[] bs = digest.digest(pwd.getBytes("UTF-8"));
			newPwd = new String(bs,"UTF-8");
		} catch (Exception e) {
			// TODO: handle exception
		}
		return newPwd;
	}
}
